import json

from fastapi import Depends, APIRouter
from pydantic import BaseModel

from api.picking_team.eu_rework import GetEudata, SubmitoneEudata, SubmitEudata, GetEudata_y
from util.JWT import get_current_user

Eu = APIRouter()


@Eu.get("/echartdata")
async def echartdata(id: dict = Depends(get_current_user)):
    df = GetEudata_y()
    if df.empty:
        return {
            "code": 204,
            "status": "no",
            "msg": "没有内容",
            "data": []
        }
    df['NRC_Time'] = df['NRC_Time'].astype(str)
    # 将DataFrame转换为字典列表
    dict_list = df.to_dict(orient='records')
    # 将字典列表转换为指定格式的JSON字符串
    json_data = json.dumps(dict_list)
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "data": json_data
    }


# 获取所有欧盟返工数据
@Eu.get("/eu_rework")
async def eu_rework(page: int = 1, page_size: int = 10, id: dict = Depends(get_current_user)):
    df = GetEudata()
    if df.empty:
        return {
            "code": 200,
            "status": "no",
            "msg": "没有内容",
            "total": 0,
            "sumqty": 0,
            "data": []
        }
    df.fillna('', inplace=True)
    total = len(df)
    sumqty = int(df['Qty'].sum())
    offset = (page - 1) * page_size
    df = df.iloc[offset: offset + page_size]
    # 将DataFrame转换为字典列表
    dict_list = df.to_dict(orient='records')
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "total": total,
        "sumqty": sumqty,
        "data": dict_list
    }


# 提交一个欧盟返工数据
class SubmitoneEudataType(BaseModel):
    ContractNO: str
    CN_Name: str
    PCS: int
    Qty: int


@Eu.post("/submitone_eu_rework")
async def submitone_eu_rework(data: SubmitoneEudataType, id: dict = Depends(get_current_user)):
    bo = SubmitoneEudata(data.ContractNO, data.CN_Name, data.PCS, data.Qty)
    if bo:
        return {
            "code": 200,
            "status": "ok",
            "msg": "success",
            "data": {}
        }
    else:
        return {
            "code": 204,
            "status": "no",
            "msg": "提交失败",
            "data": {}
        }


# 批量提交EU返工数据
class SubmitEudataType(BaseModel):
    data: list[SubmitoneEudataType]


@Eu.post("/submit_all_eu_rework")
async def submit_all_eu_rework(data: SubmitEudataType, id: dict = Depends(get_current_user)):
    data_list = data.data
    bo = SubmitEudata(data_list)
    if bo:
        return {
            "code": 200,
            "status": "ok",
            "msg": "success",
            "data": {}
        }
    else:
        return {
            "code": 204,
            "status": "no",
            "msg": "提交失败",
            "data": {}
        }
